<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>POST请求</h1>
  <form id="form" action="">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="text" name="sex">
    <button id="btn">点击获取请求</button>
  </form>
  <script>
    // 获取元素
    const oform = document.getElementById('form')
    const oname = document.querySelector('#form input[name=name]')
    const oage = document.querySelector('#form input[name=age]')
    const osex = document.querySelector('#form input[name=sex]')
    const btn = document.querySelector('#btn')

    // 绑定事件
    oform.onsubmit = function () {
      // 获取文本框内的内容
      const nameValue = oname.value
      const ageValue = oage.value
      const sexValue = osex.value

      // 创建ajax实例
      const xhr = new XMLHttpRequest()
      // 打开路径
      xhr.open('POST', '/adduser', true)
      // 发送请求
      // 由于post有多种传参方式,所以需要设置响应头
      xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
      xhr.send(JSON.stringify({
        name: nameValue,
        age: ageValue,
        sex: sexValue
      }))
      // 绑定事件
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
          console.log(JSON.parse(xhr.responseText));
        }
      }
      return false
    }
  </script>
</body>

</html>